import axios from "axios"
import router from "../router"

import { ElMessage } from 'element-plus'
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';

axios.interceptors.request.use(
    config => {
        let auth= getCookie('Authorization')
        if (auth) {  // 判断是否存在token，如果存在的话，则每个http header都加上token
            config.headers.authorization = auth;
        }
        return config;
    },
    err => {
        return Promise.reject(err);
    }
)

axios.interceptors.response.use(response => {
    if (response.status && response.status == 200){
      if (response.data.code == 500 || response.data.code == 401 || response.data.code == 403||response.data.code == -1){
          // ElMessage({
          //     dangerouslyUseHTMLString: true,
          //     message: '<strong>'+response.data.message+'</strong>'
          // });
          return response;
      }
        if ('未登录'===response.data){
                ElMessage({
                    dangerouslyUseHTMLString: true,
                    message: '<strong>'+response.data+'</strong>'
                });
        }
      // if (response.data.message){
      //     ElMessage({
      //         dangerouslyUseHTMLString: true,
      //         message: '<strong>'+response.data.message+'</strong>'
      //     });
      // }

    }
    return response;
}, error => {

    if (error.response.code==504||error.response.code==404){
        ElMessage({
            dangerouslyUseHTMLString: true,
            message: '服务器出故障了'
        });
    }else if (error.response.code==403){
        ElMessage({
            dangerouslyUseHTMLString: true,
            message: '权限不足'
        });
    }else if (error.response.code==401){
        ElMessage({
            dangerouslyUseHTMLString: true,
            message: '未登录'
        });
        router.replace("/").then(r => {

        })
    }else{
        if (error.response.data.message){
            ElMessage({
                dangerouslyUseHTMLString: true,
                message: error.response.data.message
            });
        }else {
            ElMessage({
                dangerouslyUseHTMLString: true,
                message: '未知错误'
            });
        }
    }
    return Promise.resolve(error.response)
});


let base='';

export const postReq=(url,param)=>{

    return axios({
        method:'post',
        url:`${base}${url}`,
        data:param
    })

}

export const getReq=(url,param)=>{

    return axios({
        method:'get',
        url:`${base}${url}`,
        data:param
    })
}

export const putReq=(url,param)=>{

    return axios({
        method:'put',
        url:`${base}${url}`,
        data:param
    })
}

export const deleteReq=(url,param)=>{
    return axios({
        method:'delete',
        url:`${base}${url}`,
        data:param
    })
}


export const clearObject=(obj)=>{
    Object.keys(obj).forEach(key => obj[key] = undefined);
}


export const getCookie=(cname)=>{
    let name = cname + "=";
    let ca = document.cookie.split(';');
    for(let i=0; i<ca.length; i++)
    {
        let c = ca[i].trim();
        if (c.indexOf(name)==0) return c.substring(name.length,c.length);
    }
    return "";
}

export const dateFormat=(time)=>{
    if (undefined ===time||''===time){
        return time
    }
    let date = new Date(time);
    let year = date.getFullYear();
    /* 在日期格式中，月份是从0开始的，因此要加0
     * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
     * */
    let month =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    // 拼接
    return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}

export const dateFormatYMD=(time)=>{
    if (undefined ===time||''===time){
        return time
    }
    let date = new Date(time);
    let year = date.getFullYear();
    /* 在日期格式中，月份是从0开始的，因此要加0
     * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
     * */
    let month =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    // 拼接
    return year + "-" + month + "-" + day;
}

export const clearCookie=()=>{
    let paths = ['/']
    let domain =[]
    let host = location.hostname
    domain.push(host)
    if(host.indexOf('www') > -1){
        domain.push(host.substr(3))
        console.log('domain',domain)
    }else if (host.indexOf('house') > -1){
        domain.push(host.substr(5))
        console.log('domain',domain)
    }
    let keys = document.cookie.match(/[^ =;]+(?=\=)/g)
    function deleteCookie(name,path,domain){
        let keys = document.cookie.match(/[^ =;]+(?=\=)/g) || []
        if(keys.indexOf(name)<0)return
        document.cookie= name + '=' + ((path)?';path='+path:'') + ((domain)?';domain='+domain:'') + ';expires=Thu,01-Jan-1970 00:00:01 GMT';
    }
    // 确保paths、domain、keys都不相同，都要进行清除
    paths.forEach(p=>{
        domain.forEach(d=>{
            keys.forEach(k=>{
                deleteCookie(k,p,d)
            })
        })
    })
}




